<template>
  <div class="home-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item
        v-for="crumb in breadcrumbs"
        :key="crumb.id"
        :to="crumb.path"
      >
        {{ crumb.name }}
      </el-breadcrumb-item>
    </el-breadcrumb>
    <div class="toolbar" v-if="!route.params.shareId">
      <div class="button-group">
        <el-button
          type="warning"
          :icon="Close"
          @click="onBatchCancleShare"
          :disabled="selectedIds.length == 0"
          >取消分享</el-button
        >
      </div>
      <div class="search-input">
        <el-input
          v-model="searchText"
          prefix-icon="Search"
          placeholder="搜索文件"
        />
      </div>
    </div>
    <div v-if="!route.params.shareId">
      <el-table
        v-loading="loading"
        :data="filteredTableData"
        ref="multipleTableRef"
        row-key="id"
        :default-sort="{ prop: 'expires', order: 'descending' }"
        @selection-change="onSelectionChange"
      >
        <!-- 选择框 -->
        <el-table-column type="selection" width="48" />
        <!-- 文件图标 -->
        <el-table-column
          prop="file.type"
          sortable
          :sort-orders="['ascending', 'descending']"
          label="类型"
          width="55"
          class-name="icon-column"
        >
          <template #default="{ row }">
            <svg class="file-icon" aria-hidden="true">
              <use :xlink:href="`#${getFileIconId(row.file?.type)}`" />
            </svg>
          </template>
        </el-table-column>
        <!-- 文件名 -->
        <el-table-column
          prop="file.filename"
          label="文件名"
          sortable
          :sort-orders="['ascending', 'descending']"
          min-width="100"
          class-name="filename-column"
        >
          <template #default="{ row }">
            <span class="underline" @click="onClickFilename(row)">
              {{ row.file.filename }}
            </span>
            <el-text
              type="danger"
              size="large"
              v-if="row.expires && new Date(row.expires) < now"
              >已过期</el-text
            >
            <el-text type="danger" size="large" v-if="row.file.isDeleted"
              >文件已删除</el-text
            >
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column
          label="操作"
          min-width="100"
          align="right"
          v-if="!isFold"
        >
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button link type="info" size="small" @click="onFileInfo(row)"
                >详情</el-button
              >
              <el-popconfirm
                title="确定要取消分享吗?"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="() => onCancelShare(row)"
              >
                <template #reference>
                  <el-button link type="warning" size="small"
                    >取消分享</el-button
                  >
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
        <!-- 分享时间 -->
        <el-table-column
          prop="createdAt"
          label="分享时间"
          sortable
          :sort-orders="['ascending', 'descending']"
          width="150"
          v-if="!isFold"
        >
          <template #default="{ row }">
            {{ formatToDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <!-- 失效时间 -->
        <el-table-column
          prop="expires"
          label="失效时间"
          sortable
          :sort-orders="['ascending', 'descending']"
          :sort-method="sortExpiresDate"
          width="150"
          v-if="!isFold"
        >
          <template #default="{ row }">
            {{ row.expires ? formatToDateTime(row.expires) : "永久有效" }}
          </template>
        </el-table-column>
        <!-- 展开折叠 -->
        <el-table-column type="expand" v-if="isFold">
          <template #default="props">
            <div class="expand-content">
              <div class="expand-info">
                <el-text type="info">{{
                  formatToDateTime(props.row.createdAt)
                }}</el-text>
                <el-text type="info">{{
                  props.row.expires
                    ? formatToDateTime(props.row.expires)
                    : "永久有效"
                }}</el-text>
              </div>
              <el-button-group>
                <el-button
                  type="info"
                  size="small"
                  @click="onFileInfo(props.row)"
                  >详情</el-button
                >
                <el-popconfirm
                  title="确定要取消分享吗?"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  @confirm="() => onCancelShare(props.row)"
                >
                  <template #reference>
                    <el-button type="warning" size="small">取消分享</el-button>
                  </template>
                </el-popconfirm>
              </el-button-group>
            </div>
          </template>
        </el-table-column>
        <!-- 空状态 -->
        <template #empty>
          <el-empty description="没有分享的文件" />
        </template>
      </el-table>
    </div>
    <div v-else>
      <el-card class="share-info-card">
        <div class="card-header">
          <div class="header-title">
            <svg class="file-icon" aria-hidden="true">
              <use :xlink:href="`#${getFileIconId(shareInfo?.file?.type)}`" />
            </svg>
            <span style="text-align: center; margin-left: 5px">{{
              shareInfo?.file?.filename
            }}</span>
          </div>
          <div>
            <el-button :icon="Download" type="primary" @click="handleDownload"
              >一键下载</el-button
            >
            <el-button :icon="Check" plain @click="handleSave"
              >存到我的空间</el-button
            >
            <el-button :icon="Link" type="success" @click="onCopy">复制链接</el-button>
          </div>
        </div>
        <div class="card-info">
          <el-text>分享者: {{ shareInfo?.user?.id }}</el-text>
          <el-text
            >创建时间: {{ formatToDateTime(shareInfo?.createdAt) }}</el-text
          >
          <el-text
            >失效时间：{{
              shareInfo?.expires
                ? formatToDateTime(shareInfo?.expires)
                : "永久有效"
            }}</el-text
          >
        </div>
      </el-card>
    </div>
  </div>

  <el-dialog
    v-model="passwordModalVisible"
    title="请输入访问密码"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    :fullscreen="isMobile"
  >
    <el-form :model="pwdForm" @submit.prevent>
      <el-form-item label="访问密码" :error="passwordError">
        <el-input
          v-model="pwdForm.pwd"
          placeholder="请输入访问密码"
          clearable
          @change="passwordError = ''"
          @keyup.enter="verifyPassword"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="verifyPassword">确认</el-button>
    </template>
  </el-dialog>

  <el-dialog
    v-model="shareInfoModalVisible"
    title="分享详情"
    :draggable="true"
    :fullscreen="isMobile"
  >
    <el-descriptions border>
      <el-descriptions-item label="文件名">{{
        shareInfo.file.filename
      }}</el-descriptions-item>
      <el-descriptions-item label="大小">{{
        formatFileSize(shareInfo.file.size)
      }}</el-descriptions-item>
      <el-descriptions-item label="修改时间">{{
        formatToDateTime(shareInfo.file.updatedAt)
      }}</el-descriptions-item>
      <el-descriptions-item label="类型"
        ><el-tag size="small">{{
          shareInfo.file.type
        }}</el-tag></el-descriptions-item
      >
      <el-descriptions-item label="上传时间">{{
        formatToDateTime(shareInfo.file.createdAt)
      }}</el-descriptions-item>
      <el-descriptions-item label="分享者">{{
        shareInfo.userId
      }}</el-descriptions-item>
      <el-descriptions-item label="分享时间">{{
        formatToDateTime(shareInfo.createdAt)
      }}</el-descriptions-item>
      <el-descriptions-item label="失效时间">{{
        shareInfo.expires ? formatToDateTime(shareInfo.expires) : "永久有效"
      }}</el-descriptions-item>
      <el-descriptions-item label="分享链接">
        <el-text type="primary"
          >{{ getShareUrl()
          }}<el-icon @click="onCopyUrl"><CopyDocument /></el-icon
        ></el-text>
      </el-descriptions-item>
      <el-descriptions-item label="提取码">
        <el-tag
          >{{ shareInfo?.pwd || "未设置"
          }}<el-icon @click="onCopypwd"><CopyDocument /></el-icon
        ></el-tag>
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <el-button @click="shareInfoModalVisible = false">关闭</el-button>
      <el-button type="primary" @click="onCopy">复制链接+提取码</el-button>
    </template>
  </el-dialog>
  <MoveDialog ref="moveDialogRef"/>
</template>
<script setup>
import { Close } from "@element-plus/icons-vue";
import { ref, computed, watch } from "vue";
import { formatToDateTime, formatFileSize } from "../utils/FormatUtil";
import { getFileIconId } from "../utils/FileIconId";
import { useRoute, useRouter } from "vue-router";
import {
  getSharesApi,
  getShareByIdApi,
  verifyShareApi,
  deleteShareApi,
  deleteSharesApi,
  getShareUrlApi,
} from "../api";
import { Download, Check, Link } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useStore } from "../stores/index";
import { useWindowSize } from "@vueuse/core";
import MoveDialog from "../components/MoveDialog.vue";

const { width } = useWindowSize();
const isMobile = computed(() => width.value < 768);
const isFold = computed(() => width.value < 900);

const store = useStore();
const now = new Date();

const route = useRoute();
const router = useRouter();

const tableData = ref([]); // 表格数据
const loading = ref(false); // 加载状态

// 密码相关状态
const passwordModalVisible = ref(false);
const pwdForm = ref({ pwd: "" });
const isPasswordVerified = ref(false);
const passwordError = ref("");

const shareInfo = ref(null);
const moveDialogRef = ref(null);


const shareInfoModalVisible = ref(false);
const searchText = ref("");
const selectedIds = ref([]); // 选中的行id

const filteredTableData = computed(() => {
  return tableData.value.filter((item) => {
    return item.file.filename.includes(searchText.value);
  });
});

const breadcrumbs = computed(() => {
  const root = { name: "文件分享", path: "/share", id: 0 };
  if (route.params.shareId) {
    return [
      root,
      {
        name: "文件分享详情",
        path: `/share/${route.params.shareId}`,
        id: route.params.shareId,
      },
    ];
  } else {
    return [root];
  }
});

const loadData = async () => {
  if (loading.value) {
    return;
  }
  loading.value = true;
  if (route.params.shareId) {
    try {
      const res = await getShareByIdApi(route.params.shareId);
      const folder = res.data;
      if ( folder.haspwd && folder.userId !== store.userInfo?.id && !isPasswordVerified.value) {
        if(route.query.pwd){
          try {
            await verifyShareApi(route.params.shareId, route.query.pwd);
            isPasswordVerified.value = true;
            shareInfo.value = folder;
            return;
          } catch (error) {
            console.error(error)
            return;
          }
        }else{
          passwordModalVisible.value = true;
          return
        }
      }else{
        shareInfo.value = folder;
        return;
      }
    } catch (error) {
      console.error("获取分享文件失败:", error);
    } finally {
      loading.value = false;
    }
  } else {
    passwordModalVisible.value = false;

    try {
      const res = await getSharesApi();
      ElMessage.success(res.message);
      tableData.value = res.data;
    } catch (error) {
      console.error("获取分享文件失败:", error);
    }
  }
  loading.value = false;
};

const verifyPassword = async () => {
  if (!pwdForm.value.pwd) {
    passwordError.value = "请输入访问密码";
    return;
  }

  try {
    await verifyShareApi(route.params.shareId, pwdForm.value.pwd);
    passwordModalVisible.value = false;
    isPasswordVerified.value = true;
    loadData();
  } catch (err) {
    passwordError.value = err.response.data.message || "验证失败";
    pwdForm.value.pwd = "";
  }
};
watch(
  () => route.params.shareId,
  (newShareId) => {
    isPasswordVerified.value = false;
    loadData(newShareId || null);
  },
  { immediate: true }
);

const onSelectionChange = (e) => {
  selectedIds.value = e.map((item) => item.id);
};
const onClickFilename = (row) => {
  if (row.expires && new Date(row.expires) < now) {
    ElMessage.error("文件已过期");
    return;
  }
  if (row.file.isDeleted) {
    ElMessage.error("文件已删除");
    return;
  }
  pwdForm.value.pwd = "";
  passwordError.value = "";
  shareInfo.value = row;

  router.push(`/share/${row.id}`);
};

const onCancel = () => {
  router.push("/share");
};

const sortExpiresDate = (a, b) => {
  if (!a.expires && !b.expires) return 0;
  if (!a.expires) return 1;
  if (!b.expires) return -1;

  return new Date(a.expires) - new Date(b.expires);
};

const onFileInfo = (row) => {
  shareInfo.value = row;
  shareInfoModalVisible.value = true;
};

const onCancelShare = async (row) => {
  try {
    await deleteShareApi(row.id);
    loadData();
  } catch (error) {
    console.error("取消分享失败:", error);
  }
};

const onBatchCancleShare = async () => {
  try {
    await deleteSharesApi(selectedIds.value);
    loadData();
  } catch (error) {
    console.error("批量取消分享失败:", error);
  }
};

async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage({ message: "复制成功", type: "success" });
    return true;
  } catch (err) {
    ElMessage({ message: "复制失败", type: "error" });
    return false;
  }
}

const getShareUrl = () => {
  return `${window.location.origin}/share/${shareInfo.value?.id}`;
};
const onCopyUrl = () => {
  copyToClipboard(getShareUrl());
};
const onCopypwd = () => {
  if (shareInfo.value.pwd) {
    copyToClipboard(shareInfo.value.pwd);
  }
};
const onCopy = () => {
  if (!shareInfo.value.pwd) {
    copyToClipboard(getShareUrl());
  } else {
    const fullUrl = `${getShareUrl()}?pwd=${shareInfo.value.pwd}`;
    copyToClipboard(fullUrl);
  }
};

const handleDownload = async () => {
  try {
    if (!shareInfo.value) {
      ElMessage.error("请先获取分享信息");
      return;
    }
    const shareId = shareInfo.value.id;
    const pwd = shareInfo.value.pwd;

    console.log("开始获取下载链接");
    console.log("分享ID", shareId);
    console.log("密码", pwd);

    const res = await getShareUrlApi(shareId, pwd);
    console.log("获取了签名" + res.signature);
    const DOWNLOAD_URL = import.meta.env.VITE_BASE_URL + "api/file/download/url/";
    const url = DOWNLOAD_URL + res.signature;
    window.open(url);
  } catch (error) {
    console.error("获取下载链接失败:", error);
  }
};

const handleSave = async () => {
  if(!store.userInfo?.id){
    ElMessage.error("请先登录");
    const redirect = encodeURIComponent(window.location.pathname);
    router.push(`/login?redirect=${redirect}`);
    return;
  }
  moveDialogRef.value.open(shareInfo.value.id, "share", shareInfo.value.pwd);
};
</script>
<style scoped>
:deep(.icon-column .cell) {
  padding: 0px !important;
}
:deep(td.filename-column .cell:hover) {
  text-decoration: underline;
}
:deep(td.filename-column .cell) {
  cursor: pointer;
}
.share-info-card {
  margin: 20px 0;
}
.card-header {
  display: flex;
  justify-content: space-between;
}
.header-title {
  display: flex;
  align-items: center;
}
.card-info {
  margin-top: 10px;
}
.card-info > span {
  margin: 0 20px;
}
</style>
